package com.yc.fruitmarket.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.yc.fruitmarket.biz.userBiz;
import com.yc.fruitmarket.biz.impl.userBizImpl;
import com.yc.fruitmarket.ems.Util;

@WebServlet("/userController/*")
public class userController extends BaseServlet {
	private userBiz ub = new userBizImpl();
	private Util util = new Util();
	private String acceptCode = "";
	private String code = "";
	private long startTime = 0;
	private String obj = "";
	private String code1="";
	//重置密码
	public void cz(HttpServletRequest req, HttpServletResponse resp) {
		String uid = req.getParameter("uid");
		int result = ub.cz(uid);
		this.send(resp, result);
	}
	//修改用户信息
	public void updateUserData(HttpServletRequest req, HttpServletResponse resp) {
		try {
			//获取根目录
			String webroot = this.getServletContext().getRealPath("/");
			String fileUploadPath = webroot + "..\\upload";
			File path = new File(fileUploadPath);	//创建文件夹对象
			if(!path.exists()) {					//没有该文件夹就新建
				path.mkdirs();
			}
			
			//开始上传
			//这里用的是原生servlet文件上传方式		smarupload	ajaxfileupload	上传库
			DiskFileItemFactory	factory = new DiskFileItemFactory(1024*1024*10, path);//工厂
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024*1024*10);								//设置文件存入最大大小
			
			//开始解析参数
			List<FileItem> fileItem = upload.parseRequest(req);		//文件集合
			//除了普通的for循环之外，还可以使用迭代器
			Iterator<FileItem> it = fileItem.iterator();			//开始迭代
			String filePath = "";									//新的路径
			Map<String, String> map = new HashMap();				//创建键值对
			String newFileName = "";
			while(it.hasNext()) {									//迭代循环，有没有下一个
				FileItem fi = it.next();							//下一个
				if(!fi.isFormField()) {	//来判断FileItem对象里面封装的数据是一个普通文本表单字段，还是一个文件表单字段
					//文件说明就是图片				是普通文本表单字段，返回一个true否则返回一个false
					InputStream is = fi.getInputStream();		//输入流
					String name = fi.getName();		//文件图片名字
					String endWith = name.substring(name.lastIndexOf("."));	//后缀
					
					//格式正确，开始写入数据
					newFileName = System.currentTimeMillis() + endWith;//存的文件名称
					filePath = fileUploadPath + "\\" + newFileName;			//文件总的存储路径
					
					//写入
					FileOutputStream fos = new FileOutputStream(new File(filePath));//输出流
					byte[] bs = new byte[1024];
					int length = -1;	//按1024大小存储一次
					while((length = is.read(bs)) != -1) {
						fos.write(bs, 0, length);
					}
					fos.flush();
					is.close();		//关闭输入流
					fos.close();	//关闭输出流
				}else {
					//说明是普通字段		存一下数据，方便后面jdbc操作
					String str = new String(fi.getString().getBytes("ISO-8859-1"), "utf-8");
					map.put(fi.getFieldName(), str);
				}
			}
			//操作数据库
			int result = ub.updateUserData(map, newFileName);
			this.send(resp, result);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//封禁用户
	public void ban(HttpServletRequest req, HttpServletResponse resp) {
		String uid = req.getParameter("uid");
		int i = 2;
		int result = ub.banner(uid, i);
		this.send(resp, result);
	}
	//解封用户
	public void noban(HttpServletRequest req, HttpServletResponse resp) {
		String uid = req.getParameter("uid");
		int i = 0;
		int result = ub.banner(uid, i);
		this.send(resp, result);
	}
	//条件查询用户信息
	public void byselect(HttpServletRequest req, HttpServletResponse resp) {
		String pagenum = req.getParameter("pagenum");
		String uname = req.getParameter("uname");
		String email = req.getParameter("email");
		String tel = req.getParameter("tel");
		String status = req.getParameter("status");
		List<Map<String, String>> list = ub.byselect(uname, email, tel, status, pagenum);
		this.send(resp, list);
	}
	//获取所有用户信息
		public void getAllUsers(HttpServletRequest req, HttpServletResponse resp) {
			List<Map<String, String>> list = ub.getAllUsers();
			this.send(resp, list);
		}
	//获取验证码
	public void sendCode(HttpServletRequest req, HttpServletResponse resp) {
		String tel = req.getParameter("tel");
		if("".equals(tel)) {
			return;
		}
		
		acceptCode =  util.sendTelCode(tel);
		String[] str = acceptCode.split(",");
        obj = (str[2].split(":")[1]).replace("}", "");
        code1 = obj.substring(1,7);
        System.out.println("验证码"+obj);
		startTime = System.currentTimeMillis();
		System.out.println(acceptCode);
		if(!"".equals(acceptCode)) {
			this.send(resp, 1);
		}else {
			this.send(resp, -1);
		}
	}
	//注册
	public void reg(HttpServletRequest req, HttpServletResponse resp) {
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String tel = req.getParameter("tel");
		String email = req.getParameter("email");
		code = req.getParameter("code");
		long overTime = System.currentTimeMillis();
		long time = overTime - startTime;
		System.out.println(time);
		System.out.println(code);
		//
		boolean flagEmail = ub.checkEmail(email);
		boolean flagTel = ub.checkTel(tel);
		boolean flagUname = ub.checkUname(uname);
		if(flagEmail||flagTel||flagUname) {
			this.send(resp, -1);//账号被注册
			System.out.println("账号被注册");
			return;
		}
		if(code1.equals(code) && (time < 60000)) {
			int reslut = ub.reg(uname, pwd, email, tel);
			this.send(resp, 1);
		}
		if(time >= 60000) {
			this.send(resp, -2);
		}
	}
	//登录
	public void login(HttpServletRequest req, HttpServletResponse resp) {
		String user = req.getParameter("user");
		String pwd = req.getParameter("pwd");
		List<Map<String, String>> list = ub.login(user,pwd);
		if(list.size() > 0) {
			req.getSession().setAttribute("userInfo", list.get(0));
			this.send(resp, list.get(0));
		}else {
			this.send(resp, -1);
			return;
		}
	}
	//获取管理员信息存本地
	public void findAdminInfo(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = ub.findAdminInfo();
		this.send(resp, list.get(0));
	}
	//获取用户信息
	public void findUserInfo(HttpServletRequest req, HttpServletResponse resp) {
		Map<String,String> map = (Map<String, String>) req.getSession().getAttribute("userInfo");
		if(map == null) {
			this.send(resp, -1);
			return;
		}else {
			this.send(resp, map);
		}
	}
	public void user(HttpServletRequest req, HttpServletResponse resp) {
		String uid = req.getParameter("uid");
		List<Map<String, String>> list = ub.user(uid);
		this.send(resp, list.get(0));
	}
	//充值
	public void userpay(HttpServletRequest req, HttpServletResponse resp) {
		try {
			//获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
			
			//设置请求参数
			AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
			alipayRequest.setReturnUrl(AlipayConfig.return_url);
			alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
			
			//商户订单号，商户网站订单系统中唯一订单号，必填
			Random r = new Random();
			int ono = r.nextInt(900000000)+100000000;
			String out_trade_no = new String(String.valueOf(ono).getBytes("ISO-8859-1"),"UTF-8");
			//String uid = new String(req.getParameter("uid").getBytes("ISO-8859-1"),"UTF-8");
			//String cids = new String(req.getParameter("cids").getBytes("ISO-8859-1"),"UTF-8");
			//System.out.println(uid+"uid1111111111");
			//System.out.println(cids+"cids22222222222222");
			//付款金额，必填
			String total_amount = new String(req.getParameter("countmoneys").getBytes("ISO-8859-1"),"UTF-8");
			//订单名称，必填
			String subject = new String(new String("果蔬商城").getBytes("ISO-8859-1"),"UTF-8");
			//商品描述，可空
			String body = new String(new String("好吃不贵").getBytes("ISO-8859-1"),"UTF-8");
			
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
					+ "\"total_amount\":\""+ total_amount +"\"," 
					+ "\"subject\":\""+ subject +"\"," 
					+ "\"body\":\""+ body +"\"," 
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
			
			//若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
			//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
			//		+ "\"total_amount\":\""+ total_amount +"\"," 
			//		+ "\"subject\":\""+ subject +"\"," 
			//		+ "\"body\":\""+ body +"\"," 
			//		+ "\"timeout_express\":\"10m\"," 
			//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
			//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
			
			//请求
			String result = alipayClient.pageExecute(alipayRequest).getBody();
			
			//输出
			this.send(resp, result);
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
	}
	public void sendDataToServer(HttpServletRequest req, HttpServletResponse resp) {
		Map<String,String> map = (Map<String, String>) req.getSession().getAttribute("userInfo");
		String uid = map.get("uid");
		String quans = req.getParameter("quans");
		System.out.println("优惠折扣："+quans);
		int result = ub.sendDataToServer(quans, uid);
		this.send(resp, result);
		
	}
	
	
}
